package com.framework.util.generator.db;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.framework.util.generator.vo.Column;
import com.framework.util.generator.vo.Table;

/**
 * Mysql Metadata读取
 * 
 * @Author: lbl 543414648@qq.com
 * @Date: 2014-7-24 下午1:55:11
 */
public class Mysql extends DataSource {

	public static void main(String[] args) {
		try {
			DataSource dataSource = DbFactory.create();
			Table table = dataSource.getTable("base_user");
			for (Column column : table.getColumns()) {
				System.out.println(column.getName());
				System.out.println(column.getType());
				System.out.println(column.getComment());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Table getTable(String tableName) throws SQLException {
		this.connectionTest(conn);
		Table t = new Table(tableName, new ArrayList<Column>());
		ResultSet rs = null;
		try {
			DatabaseMetaData dmd = conn.getMetaData();// 获取数据库的MataData信息
			rs = dmd.getColumns(null, "", tableName, "");
			while (rs.next()) {
				// 这里没有提供获取当前列是否主键/外键的信息提示
				Column col = new Column();
				col.setName(rs.getString("COLUMN_NAME"));
				col.setType(rs.getString("TYPE_NAME"));
				col.setComment(rs.getString("REMARKS"));
				col.setSize(rs.getInt("COLUMN_SIZE"));
				col.setNullable(rs.getBoolean("NULLABLE"));
				col.setDigits(rs.getInt("DECIMAL_DIGITS"));
				col.setDefaultValue(rs.getString("COLUMN_DEF"));
				t.getColumns().add(col);
			}
		} catch (SQLException e) {
			throw e;
		} finally {
			close(conn, null, rs);
		}
		return t;
	}

	@Override
	public List<Table> getTables() throws SQLException {
		this.connectionTest(conn);
		List<Table> tables = null;
		Table t = null;
		ResultSet rs = null;
		try {
			DatabaseMetaData dmd = conn.getMetaData();
			rs = dmd.getTables("", "", "%", null);
			tables = new ArrayList<Table>();
			while (rs.next()) {
				t = new Table();
				t.setTableName(rs.getString("TABLE_NAME"));
				tables.add(t);
			}
		} catch (SQLException e) {
			throw e;
		} finally {
			close(conn, null, rs);
		}
		return tables;
	}

}
